package diploma

import (
	"errors"
	"public_security/databases"
	"public_security/models"
)

func CreateTitle(req *models.DiplomaTitle) error {
	if err := databases.DbDefault.Model(&models.DiplomaTitle{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func UpdateTitle(req *models.DiplomaTitle) error {
	if err := databases.DbDefault.Model(&models.DiplomaTitle{}).Where("id=?", req.Id).Updates(map[string]interface{}{"name": req.Name}).Error; err != nil {
		return err
	}
	return nil
}

func RemoveTitle(req *models.DiplomaTitle) error {
	var count int
	databases.DbDefault.Model(&models.Diploma{}).Select("count(id)").Where("diploma_title_id=?", req.Id).Scan(&count)
	if count > 0 {
		return errors.New("正在使用的称号，不支持删除")
	}
	if err := databases.DbDefault.Model(&models.DiplomaTitle{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func QueryTitle(req *models.DiplomaTitle) []*models.DiplomaTitle {
	arts := make([]*models.DiplomaTitle, 0)
	databases.DbDefault.Model(req).Find(&arts)
	return arts
}
